//
//  MyBankCardVC.m
//  MRBang
//
//  Created by 铅笔 on 16/4/20.
//  Copyright © 2016年 杭州易网新科技. All rights reserved.
//

#import "MyBankCardVC.h"
#import "AddBankCardVC.h"
//#import "BankCardDetailVC.h"

#import "MyBankCardCell.h"
#import "MyBankCardModel.h"

#define CELLHEIGHT 195*PROPORTION_WIDTH

static int from =0;

@interface MyBankCardVC ()<UITableViewDataSource,UITableViewDelegate>
{
    UIButton *button_addBank;
    UIBarButtonItem *rightItem;
    
    BOOL isEdit;//是编辑 完成
    
    MyBankCardModel *model_pathBanknid;//传递bankID
    
    int tag;
}

@property (nonatomic,strong) UITableView *tableView_myBankCard;

@property (nonatomic,strong) NSMutableArray *mutableArray_data;//存放所有数

@end

@implementation MyBankCardVC

- (NSMutableArray *)mutableArray_data
{
    if (!_mutableArray_data) {
        _mutableArray_data = [[NSMutableArray alloc] init];
    }
    return _mutableArray_data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的银行卡";
    
    self.view.backgroundColor = COLOR_EVERYVIEWBG;
    
    rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editAndDoneAction)];

    self.navigationItem.rightBarButtonItem = rightItem;
    rightItem.tintColor = [UIColor whiteColor];
    
    isEdit = YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.mutableArray_data removeAllObjects];
    //网络数据请求
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self DataSourceRequestMyBankCardVCListView];
    
}

#pragma mark --- 底部加上一个 添加按钮
- (void) initWithAddBankCardButton
{
    //button  add card
    button_addBank = [[UIButton alloc] initWithFrame:CGRectMake(0,kScreenHeight-95*PROPORTION_WIDTH, kScreenWidth, 95*PROPORTION_WIDTH)];
    [self.view addSubview:button_addBank];

    button_addBank.backgroundColor = COLOR_BUTTON;
    [button_addBank setTitle:@"添加银行卡" forState:UIControlStateNormal];
    [button_addBank setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button_addBank.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_18*2]];
    [button_addBank addTarget:self action:@selector(enterIntoAddCarViewAction) forControlEvents:UIControlEventTouchUpInside];
}

//编辑 完成
- (void) editAndDoneAction
{

    if (isEdit==YES) {
        rightItem.title = @"完成";
        isEdit = NO;
        
        [self.tableView_myBankCard removeFromSuperview];
        
        [self initWithMyBankCardVCSubviews];
        [button_addBank removeFromSuperview];
        
        return;
    }
    if (isEdit == NO) {
        rightItem.title = @"编辑";
        isEdit = YES;
        
        [self.tableView_myBankCard removeFromSuperview];
        
        [self initWithMyBankCardVCSubviews];
        [self initWithAddBankCardButton];
        
        return;
    }
}

//进入添加银行卡界面
- (void) enterIntoAddCarViewAction
{
    AddBankCardVC *addBankCardView = [[AddBankCardVC alloc] init];
    [self.navigationController pushViewController:addBankCardView animated:NO];
}

#pragma mark --- 创建明细表
- (void) initWithMyBankCardVCSubviews
{
    self.tableView_myBankCard = [[UITableView alloc] init];
    if (isEdit==YES) {
        self.tableView_myBankCard.frame = CGRectMake(0,64, kScreenWidth,kScreenHeight-64-95*PROPORTION_WIDTH);
    }
    else
    {
       self.tableView_myBankCard.frame = CGRectMake(0,64, kScreenWidth,kScreenHeight-64);
    }
    
    [self.view addSubview:self.tableView_myBankCard];
    self.tableView_myBankCard.dataSource = self;
    self.tableView_myBankCard.delegate = self;
    self.tableView_myBankCard.showsVerticalScrollIndicator = NO;
    self.tableView_myBankCard.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView_myBankCard.backgroundColor = COLOR_EVERYVIEWBG;
    
    //上下拉刷新
    [self setUprefresh];
    
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mutableArray_data.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellMyBankCardID = @"cellCardRecordID";
    
    MyBankCardCell *cell_myBankCard = [tableView dequeueReusableCellWithIdentifier:cellMyBankCardID];
    if (cell_myBankCard == nil) {
        cell_myBankCard = [[MyBankCardCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellMyBankCardID];
    }
    
    cell_myBankCard.backgroundColor = COLOR_EVERYVIEWBG;
    
    UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(27*PROPORTION_WIDTH, CELLHEIGHT-1, kScreenWidth, 1.0)];
    [cell_myBankCard.contentView addSubview:view_line];
    view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];
    
    cell_myBankCard.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.mutableArray_data.count!=0) {
        [cell_myBankCard initWithCarRecordModel:self.mutableArray_data[indexPath.row]];
        
        
        UIButton *button_delete = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-120*PROPORTION_WIDTH, 72.5*PROPORTION_WIDTH, 100*PROPORTION_WIDTH, 50*PROPORTION_WIDTH)];
        [cell_myBankCard addSubview:button_delete];
        
        button_delete.backgroundColor = COLOR_BUTTON;
        [button_delete setTitle:@"删除" forState:UIControlStateNormal];
        [button_delete setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button_delete.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_30]];
        button_delete.layer.cornerRadius = 3.0;
        button_delete.clipsToBounds = YES;
        button_delete.layer.borderColor = [UIColor whiteColor].CGColor;
        button_delete.layer.borderWidth = 0.8;
        button_delete.tag = indexPath.row+30;
        [button_delete addTarget:self action:@selector(deleteDataAction:) forControlEvents:UIControlEventTouchUpInside];
        
        if (isEdit==NO) {
            button_delete.hidden = NO;
            
        }
        if (isEdit == YES) {
            button_delete.hidden = YES;
           
        }
        
        MyBankCardModel *modelValue = self.mutableArray_data[indexPath.row];
        
        if ([modelValue.bankname containsString:@"农业"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#14a795"];
            
        }
        if ([modelValue.bankname containsString:@"中国银行"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#e15560"];
            
        }
        if ([modelValue.bankname containsString:@"建设"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#1960b4"];
            
        }
        if ([modelValue.bankname containsString:@"邮政"]) {
           
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#df5661"];
            
        }
        if ([modelValue.bankname containsString:@"中信"]) {
          
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#df5560"];
            
        }
        if ([modelValue.bankname containsString:@"光大"]) {
            
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#e54ba0"];
            
        }
        if ([modelValue.bankname containsString:@"兴业"]) {
          
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#1960b3"];
            
        }
        if ([modelValue.bankname containsString:@"工商"]) {
         
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#df5763"];
        }
        
        if ([modelValue.bankname containsString:@"招商"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#f05865"];
        }
        if ([modelValue.bankname containsString:@"交通"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#186ac8"];
        }
        if ([modelValue.bankname containsString:@"华夏"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#ef5764"];
        }
        if ([modelValue.bankname containsString:@"深圳发展"]) {
             button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#31b4f4"];
        }
        if ([modelValue.bankname containsString:@"民生"]) {
           button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#33b5f4"];
        }
        if ([modelValue.bankname containsString:@"平安"]) {
            button_delete.backgroundColor = [BaseViewController colorWithHexString:@"#fa7226"];
        }
    }
    
    return cell_myBankCard;
    
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    BankCardDetailVC *bankCardDetail = [[BankCardDetailVC alloc] init];
//    [self.navigationController pushViewController:bankCardDetail animated:NO];
    
    if ([self.fromWhere isEqualToString:@"withdrawcash"] && isEdit == YES) {
        if ([self.dalegateWithDraw respondsToSelector:@selector(withDrawCashChoseMybankCard:)]) {
            [self.dalegateWithDraw withDrawCashChoseMybankCard:self.mutableArray_data[indexPath.row]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CELLHEIGHT;
}

//删除数据
- (void) deleteDataAction:(UIButton *) sender
{
    model_pathBanknid =  self.mutableArray_data[sender.tag-30];
    
    tag = sender.tag-30;
    
    [self administrationBankCardAction];
}

//管理银行卡 执行事件
- (void) administrationBankCardAction
{
    
    // 类方法
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil
                                            buttonTitles:@[@"确定"]
                                          redButtonIndex:-1
                                                delegate:self];
    
    [sheet show];
    
}

#pragma mark - LCActionSheet 代理方法

- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
    
    NSLog(@"> Clicked Index: %ld", (long)buttonIndex);
    if (buttonIndex==0) {
        [self DataSourceRequestdelete:model_pathBanknid.banknid];
    }
}

#pragma mark - 集成下拉刷洗 上拉加载
- (void)setUprefresh
{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView_myBankCard.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    //    [self.tableView.header beginRefreshing];
}

#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    from=0;
    
    [self DataSourceRequestMyBankCardVCListView];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.tableView_myBankCard.header endRefreshing];
    
}


#pragma mark -- 网络数据请求
//删除 银行卡
- (void) DataSourceRequestdelete:(NSString *)banknid
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        //删除 银行卡
        NSString *strUrl = [NSString stringWithFormat:@"%@member/delbank",MRAPI];
        NSDictionary *paras_loan = @{@"bandkid":banknid};
        
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:strUrl parameters:paras_loan success:^(id obj) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSLog(@"member/debank%@",obj);
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                [UIView showAlertMsg:@"删除成功"];
                [self.mutableArray_data removeObjectAtIndex:tag];
                
                [self.tableView_myBankCard reloadData];
                
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            [self.tableView_myBankCard reloadData];
            
        } fail:^(NSError *error) {
            NSLog(@"get%@",error);
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UIView showAlertMsg:@"网络请求超时"];
            
        }];
    }
}

#pragma mark -- 网络数据请求
//我的银行卡列表
- (void) DataSourceRequestMyBankCardVCListView
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@member/mybank",MRAPI];
        NSDictionary *paras_loan = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"]};
        
        [[HttpRequest shardWebUtil] getNetworkRequestURLString:strUrl parameters:paras_loan success:^(id obj) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSLog(@"ember/mybank%@",obj);
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                
                //当有数据的时候在进行 删除操作
                [self.mutableArray_data removeAllObjects];
                
                NSArray *array_data = obj[@"data"];
                if (array_data.count!=0) {
                    for (int i=0; i<array_data.count; i++) {
                        MyBankCardModel *model = [[MyBankCardModel alloc] init];
                        [model decodeDic:array_data[i]];
                        [self.mutableArray_data addObject:model];
                    }
                }
                else
                {
                    [BaseViewController showMessage:@"暂无数据"];
                }
                
                [self initWithMyBankCardVCSubviews];
                [self initWithAddBankCardButton];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            NSLog(@"get%@",error);
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UIView showAlertMsg:@"网络请求超时"];
            
        }];
        
    }
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.tableView_myBankCard removeFromSuperview];
    
    [button_addBank removeFromSuperview];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
